package com.example.bookmall.controller.cartFuntion;


import com.example.bookmall.entity.Book;
import com.example.bookmall.entity.Cart;
import com.example.bookmall.entity.Result;
import com.example.bookmall.mapper.CartMapper;
import com.example.bookmall.service.BookService;
import com.example.bookmall.service.CartService;
import com.example.bookmall.service.UserService;
import com.example.bookmall.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/cart")

public class CartController{

    @Autowired
    private CartService cartService;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private BookService bookService;

    //添加商品到购物车
    @PostMapping("/add")
    public Result addToCart(
            @RequestParam Integer bookId,
            @RequestParam(required = false, defaultValue = "1") Integer quantity) {

        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("userId");

        if (!bookService.existsById(bookId)) {
            return Result.error("图书不存在");
        }

        Book book = bookService.getById(bookId);
        if (book.getStatus() == 0) {
            return Result.error("图书已下架");
        }

        // 获取购物车中已有的该商品数量
        Cart existingCartItem = cartService.findCartById(userId,  bookId);
        int existingQuantity = existingCartItem != null ? existingCartItem.getQuantity() : 0;

        // 检查总数量是否超过库存
        if (existingQuantity + quantity > book.getStock()) {
            return Result.error("库存不足，最多可添加 " + (book.getStock() - existingQuantity) + " 件");
        }

        boolean result = cartService.addToCart(userId, bookId, quantity);
        if (result) {
            return Result.success("添加成功");
        } else {
            return Result.error("添加失败");
        }
    }

    //获取购物车中的商品列表
    @GetMapping("/list/{userId}")
    public Result getCartItems(@PathVariable Integer userId) {
        List<Cart> cartItems = cartService.getCartItems(userId);
        return Result.success(cartItems);
    }

    //从购物车中删除商品
    @DeleteMapping("/remove/{cartId}")
    public Result removeFromCart(@PathVariable Integer cartId) {
        boolean result = cartService.removeFromCart(cartId);
        if (result) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    //从购物车中批量删除商品
    @DeleteMapping("/remove")
    public Result removeByIds(@RequestParam List<Integer> cartIds) {

        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("userId");
        return cartService.removeByIds(cartIds,  userId)
                ? Result.success("删除成功")
                : Result.error("删除失败");
    }

    // 更新购物车商品数量
    @PostMapping("/updateQuantity")
    public Result decreaseQuantity(
            @RequestParam Integer bookId,
            @RequestParam(required = false, defaultValue = "1") Integer quantity) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("userId");

        try {
            boolean result = cartService.updateCartQuantity(userId, bookId, quantity);
            if (result) {
                return Result.success("操作成功");
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }



}